package com.example.turnoverwarning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.turnoverwarning.dto.ShopAlertInfo;
import com.example.turnoverwarning.entity.Order;
import com.example.turnoverwarning.entity.Shop;
import com.example.turnoverwarning.mapper.OrderMapper;
import com.example.turnoverwarning.mapper.ShopMapper;
import com.example.turnoverwarning.service.AlertService;
import com.example.turnoverwarning.service.EmailService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class AlertServiceImpl implements AlertService {
    private ShopMapper shopMapper;
    private OrderMapper orderMapper;
    private EmailService emailService;


    /**
     * 检查当日营业额并发送预警邮件
     */
    @Override
    @Transactional(readOnly = true)
    public void checkDailySalesAndAlert() {
        // 0. 获取时间范围（统一时间变量）
        LocalDateTime start = LocalDate.now().atStartOfDay();
        LocalDateTime end = LocalDateTime.now();

        // 1. 获取所有店铺
        List<Shop> shops = shopMapper.selectList(new QueryWrapper<Shop>().isNotNull("mail"));
        List<Long> shopIds = shops.stream().map(Shop::getId).collect(Collectors.toList());

        // 2. 批量查询所有相关订单（优化性能）
        Map<Long, List<Order>> ordersByShop = shopIds.isEmpty() ?
                Collections.emptyMap() :
                orderMapper.selectList(
                        new LambdaQueryWrapper<Order>()
                                .in(Order::getShopId, shopIds)
                                .between(Order::getCreateTime, start, end)
                ).stream().collect(Collectors.groupingBy(Order::getShopId));

        // 3. 构建预警数据（包含订单明细）
        Map<String, List<ShopAlertInfo>> alertMap = shops.stream()
                .map(shop -> {
                    // 计算总销售额
                    BigDecimal sales = Optional.ofNullable(ordersByShop.get(shop.getId()))
                            .orElse(Collections.emptyList())
                            .stream()
                            .map(Order::getAmount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    // 注入订单明细
                    return new ShopAlertInfo(
                            shop,
                            sales,
                            ordersByShop.getOrDefault(shop.getId(), Collections.emptyList())
                    );
                })
                .filter(info -> info.getTotalSales().compareTo(info.getShop().getThreshold()) < 0)
                .collect(Collectors.groupingBy(info -> info.getShop().getMail()));

        // 4. 发送邮件（逻辑保持不变）
        alertMap.forEach((mail, list) -> emailService.sendAggregatedAlertEmail(mail, list));
    }
}